import {Button, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader} from "@nextui-org/react";
import cookie from "react-cookies";
import {Token, UserName} from "@/app/constants/authTokenConstants";
import React, { useState } from "react";
import PubSub from "pubsub-js"
import axios from "axios";
import ToastUtil from "@/app/utils/toastUtil";

/**
 * 退出登录API调用
 * @returns {Promise<boolean>} 是否成功注销
 */
async function logoutService(): Promise<boolean> {
    try {
        // 获取Token
        const token = cookie.load(Token);
        const authHeader = token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '';
        
        // 调用注销API
        const response = await axios.post('/app/user/logout', {}, {
            headers: {
                'Authorization': authHeader
            }
        });
        
        const data = response.data;
        if (data && data.status) {
            return true;
        }
        return false;
    } catch (error) {
        console.error("退出登录失败", error);
        return false;
    }
}

/**
 * 退出登录组件
 * @param isExit
 * @param setExit
 * @constructor
 */
export default function ExitLogin({isExit, setExit}: any) {
    const [isLoggingOut, setIsLoggingOut] = useState(false);
    
    const handleLogout = async () => {
        setIsLoggingOut(true);
        
        try {
            // 调用注销API
            await logoutService();
            
            // 无论API是否成功，都清除本地凭证
            cookie.remove(UserName);
            cookie.remove(Token);
            
            // 重新加载页面
            window.location.reload();
        } catch (error) {
            ToastUtil("退出登录时出错，请重试", '❌', "error");
            setIsLoggingOut(false);
        }
    };
    
    return (
        <Modal
            backdrop="blur"
            placement={'auto'}
            isOpen={isExit}
            onOpenChange={setExit}
            hideCloseButton={true}
            size="sm"
        >
            <ModalContent>
                {(onClose) => (
                    <>
                        <ModalHeader className="flex flex-col gap-1 dark:text-white light:text-black text-center">退出登录</ModalHeader>
                        <ModalBody>
                            <p className={`dark:text-white light:text-black text-center`}>
                                您确定要退出登录吗？
                            </p>
                        </ModalBody>
                        <ModalFooter className="flex justify-center gap-2">
                            <Button color="default" variant="flat" onPress={onClose} disabled={isLoggingOut}>
                                取消
                            </Button>
                            <Button 
                                color="danger" 
                                variant="flat" 
                                onPress={handleLogout}
                                isLoading={isLoggingOut}
                                disabled={isLoggingOut}>
                                确定退出
                            </Button>
                        </ModalFooter>
                    </>
                )}
            </ModalContent>
        </Modal>
    )
}